<template>
  <a-config-provider>
    <div class="template-management">
      <!-- 页面头部 -->
      <div style="width: 100%; display: flex; justify-content: space-between">
        <a-breadcrumb>
          <a-breadcrumb-item><a href="/">首页</a></a-breadcrumb-item>
          <a-breadcrumb-item><a href="/#/agent/code-generator">代码生成器</a></a-breadcrumb-item>
          <a-breadcrumb-item>自定义模板</a-breadcrumb-item>
        </a-breadcrumb>
        <a-button type="primary" size="large" @click="showAddModal = true" :icon="h(PlusOutlined)">
          新建模板
        </a-button>
      </div>

      <!-- 模板网格 -->
      <a-spin :spinning="loading" tip="加载中..." size="large">
        <div class="title">内置模板</div>

        <a-row :gutter="[24, 24]" class="template-grid">
          <a-col
            :xs="{ span: 24 }"
            :sm="{ span: 12 }"
            :md="{ span: 8 }"
            :lg="{ span: 6 }"
            v-for="template in defaultTemplates"
            :key="template.id"
          >
            <a-card hoverable class="template-card" :bodyStyle="{ padding: '16px' }">
              <!-- 卡片标题 -->
              <template #title>
                <div class="card-title-wrapper">
                  <h3 class="card-title">{{ template.templateName }}</h3>
                </div>
              </template>

              <!-- 元信息 -->
              <div class="template-meta">
                <a-tag :color="getOrmColor(template.ormType)" size="small">
                  {{ template.ormType }}
                </a-tag>
                <span class="update-time">
                  {{ template.createdDate }}
                </span>
              </div>

              <!-- 操作区 -->
              <template #actions>
                <div class="card-actions">
                  <a-tooltip title="克隆模板">
                    <a-button type="text" size="small" @click="cloneTemplate(template)">
                      <template #icon>
                        <SnippetsOutlined />
                      </template>
                    </a-button>
                  </a-tooltip>
                </div>
              </template>
            </a-card>
          </a-col>
        </a-row>

        <div class="title">我的模板</div>

        <a-row :gutter="[24, 24]" class="template-grid">
          <a-col
            :xs="{ span: 24 }"
            :sm="{ span: 12 }"
            :md="{ span: 8 }"
            :lg="{ span: 6 }"
            v-for="template in myTemplates"
            :key="template.id"
          >
            <a-card hoverable class="template-card" :bodyStyle="{ padding: '16px' }">
              <!-- 卡片标题 -->
              <template #title>
                <div class="card-title-wrapper">
                  <h3 class="card-title">{{ template.templateName }}</h3>
                </div>
              </template>

              <!-- 元信息 -->
              <div class="template-meta">
                <a-tag :color="getOrmColor(template.ormType)" size="small">
                  {{ template.ormType }}
                </a-tag>
                <span class="update-time">
                  {{ template.createdDate }}
                </span>
              </div>

              <!-- 操作区 -->
              <template #actions>
                <div class="card-actions">
                  <a-tooltip title="查看文件">
                    <a-button type="text" size="small" @click="handleView(template)">
                      <template #icon>
                        <EyeOutlined />
                      </template>
                    </a-button>
                  </a-tooltip>
                  <a-tooltip title="重命名">
                    <a-button type="text" size="small" @click="handleRename(template)">
                      <template #icon>
                        <EditOutlined />
                      </template>
                    </a-button>
                  </a-tooltip>
                  <a-tooltip title="删除模板">
                    <a-popconfirm
                      title="确定要删除该模板吗？此操作不可恢复"
                      ok-text="删除"
                      ok-type="danger"
                      cancel-text="取消"
                      @confirm="handleDelete(template.id)"
                    >
                      <a-button type="text" size="small" danger>
                        <template #icon>
                          <DeleteOutlined />
                        </template>
                      </a-button>
                    </a-popconfirm>
                  </a-tooltip>
                </div>
              </template>
            </a-card>
          </a-col>

          <!-- 空状态 -->
          <a-col :span="24" v-if="myTemplates.length === 0 && !loading">
            <a-empty
              image="https://gw.alipayobjects.com/zos/antfincdn/ZHrcdLPrvN/empty.svg"
              description="暂无模板，点击按钮创建一个吧！"
            >
              <template #image>
                <img
                  style="height: 40px"
                  src="https://gw.alipayobjects.com/zos/antfincdn/ZHrcdLPrvN/empty.svg"
                  alt="empty"
                />
              </template>
              <a-button type="primary" @click="openAdd">创建第一个模板</a-button>
            </a-empty>
          </a-col>
        </a-row>
      </a-spin>

      <!-- 新建模板 -->
      <a-modal
        v-model:open="showAddModal"
        title="新建模板"
        @ok="handleAdd"
        @cancel="resetAddForm"
        ok-text="创建"
        cancel-text="取消"
        width="520px"
      >
        <a-form ref="addFormRef" :model="addForm" :rules="addFormRules" layout="vertical">
          <a-form-item label="模板名称" name="templateName">
            <a-input
              v-model:value="addForm.templateName"
              placeholder="例如：Spring Boot + MyBatis Plus"
              allow-clear
            />
          </a-form-item>
          <a-form-item label="模板类型" name="ormType">
            <a-select
              v-model:value="addForm.ormType"
              placeholder="选择 ORM 框架类型"
              :options="templateTypeOptions"
            />
          </a-form-item>
        </a-form>
      </a-modal>

      <!-- 重命名 -->
      <a-modal
        v-model:open="showRenameModal"
        title="重命名模板"
        @ok="handleConfirmRename"
        @cancel="resetRenameForm"
        ok-text="确定"
        cancel-text="取消"
        width="520px"
      >
        <a-form ref="renameFormRef" :model="renameForm" :rules="renameFormRules" layout="vertical">
          <a-form-item label="新名称" name="templateName">
            <a-input
              v-model:value="renameForm.templateName"
              placeholder="输入新的模板名称"
              allow-clear
            />
          </a-form-item>
        </a-form>
      </a-modal>
    </div>
  </a-config-provider>
</template>

<script setup>
import { ref, onMounted, reactive, shallowRef, h } from 'vue'
import { message } from 'ant-design-vue'
import {
  PlusOutlined,
  EyeOutlined,
  EditOutlined,
  DeleteOutlined,
  SnippetsOutlined
} from '@ant-design/icons-vue'
import Http from '@/api/http'

import router from '@/router'

const defaultTemplates = ref([])
const myTemplates = ref([])
const loading = ref(false)
const showAddModal = ref(false)
const showRenameModal = ref(false)
const currentTemplate = shallowRef(null)

// ---------------- 新建表单 ----------------
const addFormRef = ref()
const addForm = reactive({ templateName: '', ormType: undefined })

const addFormRules = {
  templateName: [
    { required: true, message: '请输入模板名称', trigger: 'blur' },
    { max: 50, message: '名称不能超过50个字符', trigger: 'blur' }
  ],
  ormType: [{ required: true, message: '请选择模板类型', trigger: 'change' }]
}

const templateTypeOptions = [
  { value: 'jpa', label: 'JPA' },
  { value: 'mybatis', label: 'MyBatis' },
  { value: 'mybatisPlus', label: 'MyBatis Plus' }
]

// ---------------- 重命名表单 ----------------
const renameFormRef = ref()
const renameForm = reactive({ id: null, templateName: '' })

const renameFormRules = {
  templateName: [
    { required: true, message: '请输入新名称', trigger: 'blur' },
    { max: 50, message: '名称不能超过50个字符', trigger: 'blur' }
  ]
}

function openAdd() {
  showAddModal = true
}

// ================== 方法 ==================
const getTemplates = () => {
  loading.value = true
  Http.get('/api/templateInfo/findAll')
    .then((res) => {
      if (res.data) {
        defaultTemplates.value = res.data.filter((item) => item.userId === '0')
        myTemplates.value = res.data.filter((item) => item.userId !== '0')
      }
    })
    .catch((err) => {
      message.error('获取模板列表失败')
      console.error(err)
    })
    .finally(() => {
      loading.value = false
    })
}

const getOrmColor = (type) => {
  switch (type) {
    case 'jpa':
      return 'geekblue'
    case 'mybatis':
      return 'orange'
    case 'mybatisPlus':
      return 'green'
    default:
      return 'default'
  }
}

// ---------------- 新建 ----------------
const handleAdd = () => {
  addFormRef.value
    .validate()
    .then(() => {
      Http.post('/api/templateInfo', addForm)
        .then(() => {
          message.success('模板创建成功！')
          resetAddForm()
          showAddModal.value = false
          getTemplates()
        })
        .catch(() => message.error('创建失败'))
    })
    .catch(() => {})
}

const resetAddForm = () => {
  addFormRef.value?.resetFields()
  addForm.templateName = ''
  addForm.ormType = undefined
}

// ---------------- 重命名 ----------------
const handleRename = (template) => {
  currentTemplate.value = template
  renameForm.id = template.id
  renameForm.templateName = template.templateName
  showRenameModal.value = true
}

const handleConfirmRename = () => {
  renameFormRef.value
    .validate()
    .then(() => {
      Http.put(`/api/templateInfo/rename`, renameForm)
        .then((res) => {
          if (res.code === 200) {
            message.success('重命名成功！')
            showRenameModal.value = false
            getTemplates()
          }
        })
        .catch(() => message.error('重命名失败'))
    })
    .catch(() => {})
}

const resetRenameForm = () => {
  renameFormRef.value?.resetFields()
  renameForm.id = null
  renameForm.templateName = ''
  currentTemplate.value = null
}

const cloneTemplate = (template) => {
  //克隆模板
  const data = {
    baseTemplate: template.id,
    templateName: '我的自定义模板' + Date.now(),
    ormType: template.ormType
  }
  Http.post('/api/templateInfo', data)
    .then((res) => {
      if (res.code === 200) {
        message.success('克隆成功！')
        getTemplates()
      }
    })
    .catch(() => message.error('克隆失败'))
}

// ---------------- 删除 ----------------
const handleDelete = (id) => {
  Http.delete(`/api/templateInfo/${id}`)
    .then(() => {
      message.success('删除成功！')
      getTemplates()
    })
    .catch(() => message.error('删除失败'))
}

// ---------------- 查看 ----------------
const handleView = (template) => {
  router.push('/code-template/detail/' + template.id)
}

// ================== 生命周期 ==================
onMounted(() => {
  getTemplates()
})
</script>

<style scoped>
.template-management {
  padding: 24px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  height: 100vh;
  overflow-y: auto;
}

.page-header {
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  margin-bottom: 24px;
  padding: 20px 24px;
}

.template-grid {
  margin-top: 16px;
}

.template-card {
  border-radius: 12px;
  transition: all 0.3s ease;
  background: #ffffff;
  border: 1px solid #e8e8e8;
}

.template-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12) !important;
  border-color: #1890ff33;
}

.card-title-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
}

.card-title {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: #262626;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.template-meta {
  margin-top: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #8c8c8c;
}

.card-actions {
  display: flex;
  justify-content: flex-end;
  gap: 4px;
  margin-top: 8px;
}

.update-time {
  white-space: nowrap;
  font-size: 11px;
}

/* 模态框优化 */
.view-modal-wrapper .ant-modal {
  top: 20px;
}

/* 响应式优化 */
@media (max-width: 768px) {
  .template-management {
    padding: 16px;
  }

  .page-header {
    padding: 16px;
  }

  .template-grid {
    :deep(.ant-col-xs-24) {
      max-width: 100%;
    }
  }
}

.title {
  width: 100%;
  font-size: 20px;
  font-weight: 600;
  padding-bottom: 8px;
  border-bottom: 1px solid #e8e8e8;
  margin-top: 24px;
}
</style>
